package com.base.controller.coupon_api;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.base.po.coupon.QueryOrderResponse;
import com.base.po.coupon.RefundOrderResponse;
import com.base.po.coupon_prestore.CouponOrderPrestore;
import com.base.po.coupon_sdk.CouponInfoUtil;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Userpays;
import com.base.po.voip.Users;
import com.base.po.voip.WithdrawalsQuery;
import com.base.po.voip_coupon.CouponPayOrder;
import com.base.service.COUPON.CouponOrderPrestoreService;
import com.base.service.COUPON.CouponPayOrderService;
import com.base.service.SubscribersService;
import com.base.service.UserpaysService;
import com.base.service.UsersService;
import com.base.service.WithdrawalsQueryService;
import com.base.utils.Produce;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 365优惠券退款转账
 *
 * @author K
 */
@Controller
@RequestMapping("/couponPay")
public class CouponRefundController {
    @Autowired
    private UsersService usersService;
    @Autowired
    private SubscribersService subscribersService;
    @Autowired
    private UserpaysService userpaysService;
    @Autowired
    private WithdrawalsQueryService withdrawalsQueryService;
    @Autowired
    private CouponOrderPrestoreService couponOrderPrestoreService;
    @Autowired
    private CouponPayOrderService couponPayOrderService;



    // 支付宝公用变量
    private String serverUrl = "https://openapi.alipay.com/gateway.do"; // 支付宝网关 固定
    private String FORMAT = "json"; // 参数返回格式 固定
    private String CHARSET = "UTF-8"; // 编码集 固定
    private String SIGN_TYPE = "RSA2"; // 签名算法类型 固定

    /**
     * 提交退款申请
     *
     */
    @RequestMapping(value = "/refundApplyFor", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody NetState gasRefund(Integer flag, Integer type){
        NetState netState = new NetState(); // 返回数据对象

        if (flag == null || type == null){
            netState.setData("参数为空或错误");
            return netState;
        }

        CouponOrderPrestore order = couponOrderPrestoreService.selectByFlag(flag);
        if (order == null){
            netState.setData("未查询到优惠券订单记录");
            return netState;
        }

        CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(order.getId());
        if (order == null){
            netState.setData("未查询到支付订单记录");
            return netState;
        }

        int code = 0;
        switch (type){
            case 0:
                order.setStatus(1);
                code = couponOrderPrestoreService.updateByPrimaryKeySelective(order);
                if (code == 1){
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setJson("SUCCESS");
                    netState.setData("退款取消成功");
                }else {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setJson("FAIL");
                    netState.setData("退款取消失败");
                }
                break;
            case 1:
                RefundOrderResponse refund = CouponInfoUtil.refundOrder(order.getOrderno());
                if (refund != null && refund.getCode() == 200){
                    QueryOrderResponse query = CouponInfoUtil.queryOrder(order.getOrderno());
                    if (query != null && query.getCode() == 200){
                        order.setOrderstatus(query.getData());
                    }
                }
                code = couponOrderPrestoreService.updateByPrimaryKeySelective(order);
                if (code == 1){
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setJson("SUCCESS");
                    netState.setData("退款申请成功");
                }else {
                    netState.setErrorCode(NetState.SUCCESS_CONN);
                    netState.setJson("FAIL");
                    netState.setData("退款申请失败");
                }
                break;
        }

        return netState;
    }

    /**
     * 支付宝单笔转账到支付宝账户
     *
     */
    @RequestMapping(value = "/refundMoney", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody NetState refundMoney(String userId, Integer flag) throws AlipayApiException{
        NetState netState = new NetState(); // 返回数据对象

        if (userId == null || flag == null){
            netState.setData("参数为空或错误");
            return netState;
        }

        Subscribers sub = subscribersService.selectByPrimaryKey(userId);
        if (sub == null || sub.getDatastatus() == false){
            netState.setData("用户不存在或已冻结");
            return netState;
        }

        Users users = usersService.selectByPrimaryKey(sub.getParentid());
        if (users == null || users.getDatastatus() == false){
            netState.setData("代理商不存在或已冻结");
            return netState;
        }

        CouponOrderPrestore order = couponOrderPrestoreService.selectByFlag(flag);
        if (order == null){
            netState.setData("未查询到优惠券订单记录");
            return netState;
        }

        CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(order.getId());
        if (order == null){
            netState.setData("未查询到支付订单记录");
            return netState;
        }

        Userpays userpays = userpaysService.selectByUserID(userId, true);
        if (userpays == null || userpays.getAliaccount() == null && userpays.getAliaccount().equals("")
                || userpays.getName() == null && userpays.getName().equals("")){
            netState.setData("用户支付宝信息未配置");
            return netState;
        }

        String appId = users.getAppid();// APPID
        String privateKey = users.getKeypath();// 商户私钥
        String alipayPublicKey = users.getAlipubkey();// 支付宝公钥
        if (appId == null || privateKey == null || alipayPublicKey == null || appId.isEmpty()
                || privateKey.isEmpty() || alipayPublicKey.isEmpty()) {
            netState.setErrorCode(NetState.API_NOT_PER);
            netState.setData("应用状态异常，商户未配置信息");
            return netState;
        }

        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey,"json","UTF-8", alipayPublicKey,"RSA2");
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\""+ Produce.getUUID() +"\"," +
                "\"payee_type\":\"ALIPAY_LOGONID\"," +
                "\"payee_account\":\"" + userpays.getAliaccount() + "\"," +
                "\"amount\":\"" + payOrder.getUnitprice() + "\"," +
                "\"payee_real_name\":\"" + userpays.getName() + "\"," +
                "\"remark\":\"特权优惠券退款\"" +
                "  }");
        AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);

        if(response.isSuccess()){
            order.setStatus(3);
            couponOrderPrestoreService.updateByPrimaryKeySelective(order);
            // 返回付款成功信息
            netState.setErrorCode(NetState.SUCCESS_CONN);
            netState.setJson("SUCCESS");
            netState.setData("退款成功");
        } else {
            withdrawalsQueryService.insertSelective(new WithdrawalsQuery(Produce.getUUID(), userId, Produce.getNowDate(),
                    response.getOrderId(), response.getOutBizNo(), JSONObject.fromObject(response).toString(),
                    "付款申请订单失败"));
            netState.setErrorCode(NetState.ERROR_OPERATE);
            netState.setJson("Fail");
            netState.setData("付款申请订单失败,错误:" + JSONObject.fromObject(response).toString());
        }

        return netState;
    }
}
